#!/usr/bin/env python3
"""
Webhook测试工具
用于测试Stripe webhook功能
"""

import json
import hmac
import hashlib
import requests
from typing import Dict, Any

from config import Config


class WebhookTestTool:
    """Webhook测试工具类"""
    
    def __init__(self, webhook_url: str = None, endpoint_secret: str = None):
        self.webhook_url = webhook_url or Config.WEBHOOK_URL
        self.endpoint_secret = endpoint_secret or Config.WEBHOOK_ENDPOINT_SECRET
    
    def create_test_event(self, event_type: str, data: Dict[str, Any] = None) -> Dict[str, Any]:
        """创建测试事件数据"""
        if data is None:
            data = self._get_default_event_data(event_type)
        
        return {
            "id": f"evt_test_{event_type.replace('.', '_')}",
            "object": "event",
            "api_version": "2020-08-27",
            "created": 1234567890,
            "data": {
                "object": data
            },
            "livemode": False,
            "pending_webhooks": 1,
            "request": {
                "id": "req_test",
                "idempotency_key": None
            },
            "type": event_type
        }
    
    def _get_default_event_data(self, event_type: str) -> Dict[str, Any]:
        """获取默认的事件数据"""
        if event_type == "payment_intent.succeeded":
            return {
                "id": "pi_test_payment_success",
                "object": "payment_intent",
                "amount": 2000,
                "currency": "usd",
                "status": "succeeded",
                "customer": "cus_test_customer"
            }
        elif event_type == "customer.subscription.created":
            return {
                "id": "sub_test_subscription",
                "object": "subscription",
                "customer": "cus_test_customer",
                "status": "active",
                "current_period_start": 1234567890,
                "current_period_end": 1234567890 + 86400 * 30,
                "cancel_at_period_end": False
            }
        elif event_type == "customer.created":
            return {
                "id": "cus_test_customer",
                "object": "customer",
                "email": "test@example.com",
                "name": "Test Customer"
            }
        elif event_type == "product.created":
            return {
                "id": "prod_test_product",
                "object": "product",
                "name": "Test Product",
                "description": "A test product"
            }
        else:
            return {
                "id": f"test_{event_type.replace('.', '_')}",
                "object": "test_object"
            }
    
    def sign_payload(self, payload: str) -> str:
        """签名payload"""
        signature = hmac.new(
            self.endpoint_secret.encode('utf-8'),
            payload.encode('utf-8'),
            hashlib.sha256
        ).hexdigest()
        
        return f"whsec_{signature}"
    
    def send_test_webhook(self, event_type: str, custom_data: Dict[str, Any] = None) -> Dict[str, Any]:
        """发送测试webhook"""
        try:
            # 创建测试事件
            event_data = self.create_test_event(event_type, custom_data)
            payload = json.dumps(event_data)
            
            # 签名payload
            signature = self.sign_payload(payload)
            
            # 发送请求
            headers = {
                "Content-Type": "application/json",
                "Stripe-Signature": signature
            }
            
            response = requests.post(
                self.webhook_url,
                data=payload,
                headers=headers,
                timeout=10
            )
            
            return {
                "status_code": response.status_code,
                "response": response.json() if response.status_code == 200 else response.text,
                "event_type": event_type,
                "event_id": event_data["id"]
            }
            
        except Exception as e:
            return {
                "error": str(e),
                "event_type": event_type
            }
    
    def test_all_events(self) -> Dict[str, Any]:
        """测试所有支持的事件类型"""
        supported_events = [
            "payment_intent.succeeded",
            "payment_intent.payment_failed",
            "payment_intent.canceled",
            "customer.created",
            "customer.updated",
            "customer.deleted",
            "customer.subscription.created",
            "customer.subscription.updated",
            "customer.subscription.deleted",
            "customer.subscription.trial_will_end",
            "invoice.payment_succeeded",
            "invoice.payment_failed",
            "invoice.created",
            "invoice.updated",
            "product.created",
            "product.updated",
            "product.deleted",
            "price.created",
            "price.updated",
            "price.deleted"
        ]
        
        results = {}
        
        for event_type in supported_events:
            print(f"测试事件: {event_type}")
            result = self.send_test_webhook(event_type)
            results[event_type] = result
            
            if result.get("status_code") == 200:
                print(f"  ✅ 成功")
            else:
                print(f"  ❌ 失败: {result.get('error', result.get('response', 'Unknown error'))}")
        
        return results


def main():
    """主函数"""
    print("🚀 Webhook测试工具")
    print("=" * 50)
    
    # 创建测试工具
    test_tool = WebhookTestTool()
    
    print(f"Webhook URL: {test_tool.webhook_url}")
    print(f"Endpoint Secret: {test_tool.endpoint_secret[:10]}...")
    print()
    
    # 测试单个事件
    print("📝 测试单个事件:")
    result = test_tool.send_test_webhook("payment_intent.succeeded")
    print(f"结果: {result}")
    print()
    
    # 测试所有事件
    print("📝 测试所有支持的事件:")
    results = test_tool.test_all_events()
    
    # 统计结果
    success_count = sum(1 for r in results.values() if r.get("status_code") == 200)
    total_count = len(results)
    
    print()
    print("=" * 50)
    print(f"📊 测试结果: {success_count}/{total_count} 成功")
    
    if success_count == total_count:
        print("🎉 所有webhook测试通过！")
    else:
        print("❌ 部分webhook测试失败")


if __name__ == "__main__":
    main()
